package cloud.shyidong.admin.auth.interceptor;

import cloud.shyidong.core.Result;
import cloud.shyidong.core.context.Context;
import cloud.shyidong.core.context.ContextHolder;
import cloud.shyidong.core.exception.BusinessException;
import cloud.shyidong.core.util.MapUtils;
import cloud.shyidong.core.util.StringUtils;
import cloud.shyidong.feign.AuthServiceFeign;
import cloud.shyidong.system.entity.SystemUserEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description TODO
 * @Author syd
 * @Date 2023/4/17
 */
@Component
@Slf4j
@RefreshScope
public class AuthInterceptor implements HandlerInterceptor {
    
    private AuthServiceFeign authServiceFeign;
    
    @Autowired
    @Lazy
    public void setAuthServiceFeign(AuthServiceFeign authServiceFeign) {
        this.authServiceFeign = authServiceFeign;
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        if (log.isDebugEnabled()) {
            log.debug("servletPath >>> {}", request.getServletPath());
        }
        
        String token = request.getHeader("token");
        if (log.isDebugEnabled()) {
            log.debug("token >>> {}", token);
        }
        if (StringUtils.isEmpty(token)) {
            throw BusinessException.noLogin();
        }
        ContextHolder.setToken(token);
        
        Result result = authServiceFeign.getAdminInfo(token);
        if (MapUtils.isEmpty(result)) {
            throw BusinessException.noLogin();
        }
        if (log.isDebugEnabled()) {
            log.debug("auth result >>> {}", JSON.toJSONString(result));
        }
        
        if (!result.isLogin()) {
            throw BusinessException.noLogin();
        }
        
        String value = (String) result.get("data");
        SystemUserEntity systemUserEntity = JSON.parseObject(value, new TypeReference<SystemUserEntity>() {
        });
        
        Context context = new Context();
        context.setUserId(systemUserEntity.getId());
        ContextHolder.setContext(context);
        
        return true;
    }
    
}
